package com.ysj.aipicturebe.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ysj.aipicturebe.config.MqConfig.RabbitMQConfig;
import com.ysj.aipicturebe.constant.RedisLuaScriptConstant;
import com.ysj.aipicturebe.exception.BusinessException;
import com.ysj.aipicturebe.exception.ErrorCode;
import com.ysj.aipicturebe.mapper.ThumbMapper;
import com.ysj.aipicturebe.model.dto.thumb.DoThumbRequest;
import com.ysj.aipicturebe.model.entity.Thumb;
import com.ysj.aipicturebe.model.entity.User;
import com.ysj.aipicturebe.model.enums.LuaStatusEnum;
import com.ysj.aipicturebe.model.msg.ThumbEvent;
import com.ysj.aipicturebe.service.ThumbService;
import com.ysj.aipicturebe.service.UserService;
import com.ysj.aipicturebe.utils.RedisKeyUtil;
import lombok.RequiredArgsConstructor;
import org.apache.calcite.util.Template;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Max;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
* @author ysj
* @description 针对表【thumb】的数据库操作Service实现
* @createDate 2025-05-06 14:18:39
*/
@Service
@RequiredArgsConstructor
public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
    implements ThumbService {

    private final UserService userService;

    private final StringRedisTemplate stringRedisTemplate;

    private final RabbitTemplate rabbitTemplate;

   @Override
    public Boolean doThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        // 校验参数是否为空
        if (doThumbRequest == null || doThumbRequest.getPictureId() == null) {
            throw new RuntimeException("参数错误");
        }
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 获取用户ID
        Long loginUserId = loginUser.getId();
        // 获取图片ID
        Long pictureId = doThumbRequest.getPictureId();
        // 构造用户点赞的Redis Key
        String userThumbKey = RedisKeyUtil.getUserThumbKey(loginUserId);
        // 执行Lua脚本，将点赞信息存入Redis
        long result = stringRedisTemplate.execute(
                RedisLuaScriptConstant.THUMB_SCRIPT_MQ,
                Arrays.asList(userThumbKey),
                String.valueOf(pictureId)
        );

        // 如果Lua脚本返回失败，说明用户已点赞，抛出业务异常
        if (LuaStatusEnum.FAIL.getValue() == result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户已点赞");
        }

        // 构造点赞事件消息
        ThumbEvent thumbEvent = ThumbEvent.builder()
                .pictureId(pictureId)
                .userId(loginUserId)
                .type(ThumbEvent.EventType.INCR)
                .eventTime(LocalDateTime.now())
                .build();
        // 发送点赞事件到RabbitMQ
        rabbitTemplate.convertAndSend(RabbitMQConfig.THUMB_EXCHANGE, RabbitMQConfig.doThumb, JSONUtil.toJsonStr(thumbEvent));
        // 返回操作成功
        return true;
    }

    private String getTimeSlice() {
        DateTime nowDate = DateUtil.date();
        // 获取到当前时间前最近的整数秒，比如当前 11:20:23 ，获取到 11:20:20
        return DateUtil.format(nowDate, "HH:mm:") + (DateUtil.second(nowDate) / 10) * 10;
    }

    @Override
    public Boolean undoThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        if (doThumbRequest == null || doThumbRequest.getPictureId() == null) {
            throw new RuntimeException("参数错误");
        }
        User loginUser = userService.getLoginUser(request);
        Long loginUserId = loginUser.getId();
        Long pictureId = doThumbRequest.getPictureId();
        String userThumbKey = RedisKeyUtil.getUserThumbKey(loginUserId);
        // 执行 Lua 脚本，点赞记录从 Redis 删除
        long result = stringRedisTemplate.execute(
                RedisLuaScriptConstant.UNTHUMB_SCRIPT_MQ,
                Arrays.asList(userThumbKey),
                String.valueOf(pictureId)
        );
        if (LuaStatusEnum.FAIL.getValue() == result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户未点赞");
        }
        ThumbEvent thumbEvent = ThumbEvent.builder()
                .pictureId(pictureId)
                .userId(loginUserId)
                .type(ThumbEvent.EventType.DECR)
                .eventTime(LocalDateTime.now())
                .build();
        rabbitTemplate.convertAndSend(RabbitMQConfig.THUMB_EXCHANGE, RabbitMQConfig.doThumb, JSONUtil.toJsonStr(thumbEvent));

        return true;
    }

    @Override
    public Boolean hasThumb(Long blogId, Long userId) {
        return stringRedisTemplate.opsForHash().hasKey(RedisKeyUtil.getUserThumbKey(userId), blogId.toString());
    }
}




